package rjeutsky.database.jpa;

import java.sql.SQLException;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

import rjeutsky.database.interfaces.Repository;
import rjeutsky.models.User;
import rjeutsky.models.UserRole;

public class DatabaseInitializer {
	
	private Configuration config;
	
	public DatabaseInitializer(Configuration config) {
		this.config = config;
	}
	
	public void Initialize() throws SQLException {
		// did not found how to get valid ServiceRegistry object
		@SuppressWarnings("deprecation")
		SessionFactory factory = config.buildSessionFactory();
		SchemaExport exporter = new SchemaExport(config);
		exporter.create(false, true);
		Repository repository = new JPARepository(factory);
		UserRole adminRole = new UserRole();
		adminRole.setName(UserRole.ADMIN);
		adminRole.setId(1L);
		repository.getUserRoleRepository().create(adminRole);
		User adminUser = new User();
		adminUser.setId(1L);
		adminUser.setLogin("admin");
		adminUser.setPassword("admin");
		adminUser.setSalt("");
		repository.getReaderRepository().create(adminUser);
		repository.addRoleToUser(adminUser, adminRole);
		factory.close();
	}
	
}
